﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using ASoft.Data;

namespace ASoft.WPF.View
{
    /// <summary>
    /// AddUserView.xaml 的交互逻辑
    /// </summary>
    public partial class AddUserView : Window
    {
        UserData userData;
        public AddUserView(UserData userData)
        {
            InitializeComponent();
            this.userData = userData;

            IsDataAdded = userData == null;
            IsDataUpdated = !IsDataAdded;
            if (IsDataAdded)
            {
                this.Title = "添加用户";
            }
            else
            {
                this.Title = "修改用户";
                txtCode.Text = userData.Code;
                txtName.Text = userData.Name;
                txtPassword.Password = "*";
                txtIsAdmin.IsChecked = userData.IsAdmin;
            }
        }

        public bool IsDataChanged { get; private set; }

        public bool IsDataAdded { get; private set; }

        public bool IsDataUpdated { get; private set; }

        private void btnYes_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (string.IsNullOrEmpty(txtCode.Text))
            {
                txtMsg.Text = "用户名不能为空";
                return;
            }
            if (string.IsNullOrEmpty(txtName.Text))
            {
                txtMsg.Text = "用户名不能为空";
                return;
            }
            if (string.IsNullOrWhiteSpace(txtPassword.Password))
            {
                txtMsg.Text = "密码不能为空";
                return;
            }

            UserData user = null;
            if (IsDataAdded)
            {
                user = new UserData();
            }
            else
            {
                user = userData;
            }

            if (RC.Current.RootData.Users.Count(p => !p.Equals(user)
                && string.Equals(p.Code, txtName.Text, StringComparison.CurrentCultureIgnoreCase)) > 0)
            {
                txtMsg.Text = "用户名重复.";
                return;
            }

            user.Code = txtCode.Text.Trim();
            user.Name = txtName.Text.Trim();
            user.IsAdmin = txtIsAdmin.IsChecked == true; ;
            user.ResetPassword(txtPassword.Password);

            if (IsDataAdded)
            {
                RC.Current.RootData.Users.Add(user);
            }
            RC.Current.SaveRootData();

            IsDataChanged = true;

            if (IsDataAdded)
            {
                this.Close();
            }
        }
    }
}
